package interview.huawei.myself.online1.v2;

import java.util.ArrayDeque;

/**
 * @Author CandyWall
 * @Date 2022/3/13--11:01
 * @Description
 */
public class MessageQueue {
    private int capacity = 3;
    // 奇数队列
    private ArrayDeque<Integer> oddQueue;
    // 偶数队列
    private ArrayDeque<Integer> evenQueue;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
        oddQueue = new ArrayDeque<>(capacity);
        evenQueue = new ArrayDeque<>(capacity);
    }

    // 放奇数
    public void putOddNumber(int oddNumber) {
        synchronized (oddQueue) {
            // 队列满了就等待
            while (oddQueue.size() == capacity) {
                System.out.println("奇数队列满了，等待中...");
                try {
                    oddQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            oddQueue.addLast(oddNumber);
            oddQueue.notifyAll();
        }
    }

    // 取奇数
    public Integer getOddNumber() {
        synchronized (oddQueue) {
            while (oddQueue.isEmpty()) {
                System.out.println("奇数队列空了，等待中...");
                try {
                    oddQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Integer num = oddQueue.removeFirst();
            oddQueue.notifyAll();
            return num;
        }
    }

    // 放偶数
    public void putEvenNumber(int evenNumber) {
        synchronized (evenQueue) {
            // 队列满了就等待
            while (evenQueue.size() == capacity) {
                System.out.println("偶数队列满了，等待中...");
                try {
                    evenQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            evenQueue.addLast(evenNumber);
            evenQueue.notifyAll();
        }
    }

    // 取偶数
    public Integer getEvenNumber() {
        synchronized (evenQueue) {
            while (evenQueue.isEmpty()) {
                System.out.println("偶数队列空了，等待中...");
                try {
                    evenQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Integer num = evenQueue.removeFirst();
            evenQueue.notifyAll();
            return num;
        }
    }
}
